import json


class Player:
	def __init__(self, socket, name='anonymous'):
		self.name = name
		self.score = 0
		self.hand = []
		self.socket = socket
		self.card = None

	def set_hand(self, hand):
		self.hand = hand

	def finish_card(self):
		self.hand.remove(self.card)
		self.card = None

	def set_card(self, card):
		if card in self.hand:
			self.card = card
			return self.card
		return None

	@classmethod
	def validate_row_selection(cls, jmsg, options):
		action = jmsg.get('action')
		i = jmsg.get('i')
		if action == 'select_row' and i in options:
			return i
		return None

	def query_user(self, msg, options):
		num = None
		jmsg = {
			'type': 'query',
			'action': 'select_row',
			'rows': msg}
		bmsg = bytes(json.dumps(jmsg), 'utf-8')
		while True:
			self.socket.send(bmsg)
			ans = self.socket.recv(1024)
			try:
				jmsg = json.loads(str(ans, 'utf-8').strip())
			except json.decoder.JSONDecodeError:
				print("Decode Error", ans)
				continue
			num = Player.validate_row_selection(jmsg, options)
			if num is not None:
				break
		return num

	def select_row(self, rows):
		return self.query_user(rows, list(range(len(rows))))

	def __del__(self):
		self.name = 'DELETED'  # DEBUG
